package com.backend.demo1.middlewares;

import com.backend.demo1.annotations.JwtRequired;
import com.backend.demo1.utils.JwtUtil;
import com.backend.demo1.config.ApiException;
import com.backend.demo1.config.AppConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.slf4j.event.Level; 
import java.lang.reflect.Method;

@Component
public class JwtMiddleware implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AppConfig appConfig; // 注入 AppConfig

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            if (method.isAnnotationPresent(JwtRequired.class)) {
                String authHeader = request.getHeader("Authorization");

                if (authHeader == null || !authHeader.startsWith("Token ")) {
                    if (appConfig.isDevMode()) {
                        throw new ApiException(401, "缺少有效的 JWT Token");
                    } else {
                        throw new ApiException(401, "未登录，重新登录",Level.INFO);
                    }
                }

                String token = authHeader.substring(6);

                if (!jwtUtil.validateToken(token)) {
                    if (appConfig.isDevMode()) {
                        throw new ApiException(401, "无效或过期的 JWT Token");
                    } else {
                        throw new ApiException(401, "登录过期，重新登录",Level.INFO);
                    }
                }
            }
        }

        return true;
    }
}